package com.restkeeper.service;

import com.restkeeper.entity.OrderEntity;
import com.restkeeper.entity.ReverseOrder;
import com.restkeeper.exception.BussinessException;
import com.restkeeper.mapper.ReverseOrderMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.restkeeper.tenant.TenantContext;
import com.restkeeper.utils.SystemCode;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 反结账主表 服务实现类
 * </p>
 */
@Service(version = "1.0.0", protocol = "dubbo")
@Component
public class ReverseOrderServiceImpl extends ServiceImpl<ReverseOrderMapper, ReverseOrder> implements IReverseOrderService {

    @Autowired
    private IOrderService orderService;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean reverse(ReverseOrder reverseOrder) {
        String orderId = reverseOrder.getOrderId();
        OrderEntity orderEntity = orderService.getById(orderId);
        if(orderEntity==null){
            throw new BussinessException("该订单不支持反结账");
        }
        orderEntity.setPayStatus(SystemCode.ORDER_STATUS_NOPAY);
        orderService.updateById(orderEntity);
        String storeId = RpcContext.getContext().getAttachment("storeId");
        reverseOrder.setCreateTime(LocalDateTime.now());
        reverseOrder.setOrderNumber(storeId);
        reverseOrder.setTableId(orderEntity.getTableId());
        reverseOrder.setAmount(orderEntity.getPayAmount());
        String loginUserName = RpcContext.getContext().getAttachment("loginUserName");
        reverseOrder.setOperatorName(loginUserName);
        return this.save(reverseOrder);
    }
}
